<?php
namespace app\http;
use think\facade\Db;
use think\worker\Server;
use Workerman\Lib\Timer;
use think\facade\Log;

/**
 * websockect
 * Class Worker
 * @package app\http
 */
class Worker extends Server
{
    protected $socket = 'websocket://0.0.0.0:2346';
    /**
     * 心跳检测
     * @var inta
     */
    protected static $heartbeat_time    =   60;

    public function onConnect($connection){
        Log::info('lpb');
        $connection->send(json_encode(['message' => 'qqqw']));
    }

    ## 接收消息，接收心跳消息 ,接收用户id 信息等等
    public function onMessage($connection,$data)
    {
        $connection->lastMessageTime = time();
        Log::info('Received data: ' . 'lpd');
        $connection->send(json_encode('receive success'));
    }

    /**
     * 消息回调
     * @param $worker
     */
    public function onWorkerStart($worker)
    {
        //查看是否有新的下面的3是几秒推送一次
        Timer::add(1, function () use ($worker) {

            $time_now           = time();

            ## 推送的数据
            $infoObj =  ['name' => '刘佩东'];

            foreach ($worker->connections as $connection) {
                if (empty($connection->lastMessageTime)) {
                    $connection->lastMessageTime = $time_now;
                }

                if ($time_now - $connection->lastMessageTime > self::$heartbeat_time) {
                    $connection->close();
                }

                $connection->send(json_encode($infoObj));
            }
        });
    }

    public function onClose($connection){
        Log::info('Connection closed');
    }
}